from sqlalchemy import Column, Integer, String, DateTime, Boolean, Text, Float, ForeignKey, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from datetime import datetime
import pytz

# 定义上海时区
SHANGHAI_TZ = pytz.timezone('Asia/Shanghai')

Base = declarative_base()


class ServiceConfig(Base):
    """主备服务配置表"""
    __tablename__ = "service_configs"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True, nullable=False)
    primary_url = Column(String(500), nullable=False)
    backup_url = Column(String(500), nullable=False)
    health_check_endpoint = Column(String(200), default="/health")
    check_interval = Column(Integer, default=30)  # 秒
    timeout = Column(Integer, default=10)  # 秒
    retry_count = Column(Integer, default=3)
    is_active = Column(Boolean, default=True)
    description = Column(Text)
    # 修改为上海时区时间
    created_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))
    updated_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ), onupdate=lambda: datetime.now(SHANGHAI_TZ))

    # 关联
    health_checks = relationship("HealthCheck", back_populates="service", cascade="all, delete-orphan")
    switch_logs = relationship("SwitchLog", back_populates="service", cascade="all, delete-orphan")


class HealthCheck(Base):
    """健康检查记录表"""
    __tablename__ = "health_checks"

    id = Column(Integer, primary_key=True, index=True)
    service_id = Column(Integer, ForeignKey("service_configs.id", ondelete="CASCADE"), nullable=False)
    status = Column(String(20), nullable=False)  # healthy, unhealthy, timeout, error
    response_time = Column(Float)  # 毫秒
    http_status = Column(Integer)
    error_message = Column(Text)
    # 修改为上海时区时间
    checked_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))

    # 关联
    service = relationship("ServiceConfig", back_populates="health_checks")


class SwitchLog(Base):
    """切换记录表"""
    __tablename__ = "switch_logs"

    id = Column(Integer, primary_key=True, index=True)
    service_id = Column(Integer, ForeignKey("service_configs.id", ondelete="CASCADE"), nullable=False)
    switch_type = Column(String(20), nullable=False)  # automatic, manual
    from_status = Column(String(20), nullable=False)  # primary, backup
    to_status = Column(String(20), nullable=False)  # primary, backup
    reason = Column(Text)
    operator = Column(String(100))  # 操作人
    success = Column(Boolean, default=True)
    error_message = Column(Text)
    # 修改为上海时区时间
    created_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))

    # 关联
    service = relationship("ServiceConfig", back_populates="switch_logs")


class SystemConfig(Base):
    """系统配置表"""
    __tablename__ = "system_configs"

    id = Column(Integer, primary_key=True, index=True)
    key = Column(String(100), unique=True, index=True, nullable=False)
    value = Column(JSON)
    description = Column(Text)
    # 修改为上海时区时间
    created_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))
    updated_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ), onupdate=lambda: datetime.now(SHANGHAI_TZ))


class NotificationConfig(Base):
    """通知配置表"""
    __tablename__ = "notification_configs"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    type = Column(String(20), nullable=False)  # email, webhook, sms
    config = Column(JSON, nullable=False)  # 具体配置
    is_active = Column(Boolean, default=True)
    # 修改为上海时区时间
    created_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))
    updated_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ), onupdate=lambda: datetime.now(SHANGHAI_TZ))


class AlertRule(Base):
    """告警规则表"""
    __tablename__ = "alert_rules"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    service_id = Column(Integer, ForeignKey("service_configs.id", ondelete="CASCADE"), nullable=True)
    rule_type = Column(String(50), nullable=False)  # health_check_failure, response_time_threshold, etc
    threshold = Column(JSON)  # 阈值配置
    notification_config_id = Column(Integer, ForeignKey("notification_configs.id", ondelete="CASCADE"))
    is_active = Column(Boolean, default=True)
    # 修改为上海时区时间
    created_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ))
    updated_at = Column(DateTime, default=lambda: datetime.now(SHANGHAI_TZ), onupdate=lambda: datetime.now(SHANGHAI_TZ))